<script>
import {Popup,Swipe,SwipeItem,Stepper,Loading,Toast,} from 'vant'
import {getSellerGoods} from "@/API/commodity";
import {priceFormat,priceFormatInt,isLogin} from "@/utils/utis";
import {keepGoods, keepGoodsDel} from "@/API/commodity";
export default {
  name: "addCart",
  components: {
    [Popup.name]: Popup,
    [Loading.name]: Loading,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [Stepper.name]: Stepper,
  },
  data() {
    return {
      itemName: process.env.VUE_APP_ITEM_NAME,
      priceFormatInt,
      popupShow: false,
      loading:false,
      goods_info: {}, //商品信息
      activeAttrs: [],
      allSkus: [],
      defaultImageList: [],
      imageList: [],
      collectTitle: '',
      originalPrice: 0,
      currentSkuTitle: [],
      currentSkuId: "-1",
      currentCoverImg: '',
      maxBuyNum: localStorage.getItem('maxBuyNum') || 500,
      bugNum: 1, //购买数量
      cartNum: 0, //购物车数量
      btnDisabled: true,
      currentIndex:0,
      sellerGoodsId:'',
    };
  },
  methods: {
    onChange(index){
      this.currentIndex = index;
    },
    checkActiveDot(index) {
      return index === this.currentIndex;// currentIndex为监听的轮播index
    },
    show(id) {
      this.sellerGoodsId = id
      this.popupShow = true
      this.goods_info= {} //商品信息
      this.activeAttrs= []
      this.allSkus= []
      this.defaultImageList= []
      this.imageList= []
      this.collectTitle= ''
      this.originalPrice= 0
      this.currentSkuTitle= []
      this.currentSkuId= "-1"
      this. currentCoverImg= ''
      this.maxBuyNum= localStorage.getItem('maxBuyNum') || 500
      this.bugNum= 1 //购买数量
      this.cartNum= 0 //购物车数量
      this.btnDisabled= true
      this.currentIndex=0
      this.getInfo()
    },
    hide() {
      this.popupShow = false
    },
    getInfo(){
      this.loading = true
      let dataJson = {
        sellerGoodsId: this.sellerGoodsId,
        skuId: null,
      };
      getSellerGoods(dataJson).then((data) => {
        this.loading = false
        this.$nextTick(() => {
          this.goods_info = data;
          this.getSkusAndPrice()
        })

        if (data.canSelectAttributes?.goodAttrs?.length) {
          data.canSelectAttributes.goodAttrs.forEach((item) => {
            this.activeAttrs.push(item.attrValues[0].attrValueId);
            // if (item.attrValues[0].icon) {
            //     this.imageList = item.attrValues.map(sub => sub.iconImg)
            // }
          });
          this.allSkus = data.canSelectAttributes.skus;
          const ids = data.canSelectAttributes.goodAttrs.map(item => item.attrId)
          this.allSkus.forEach((item) => {
            item.attrs = item.attrs.sort((star, next) => ids.indexOf(star.attrId) - ids.indexOf(next.attrId))
          })
        }
        for (let i = 0; i < 10; i++) {
          if (data[`imgUrl${i + 1}`]) {
            this.defaultImageList.push(data[`imgUrl${i + 1}`]);
          }
        }
        if (!this.imageList.length) {
          this.imageList = this.defaultImageList
        }
        // this.getSellerInfo(data.seller.id);
        if (this.goods_info.isKeep == 1) {
          this.collectTitle = this.$t("已收藏");
        } else {
          this.collectTitle = this.$t("收藏");
        }
        if (!data.canSelectAttributes?.goodAttrs) {
          if (data.discountPrice) {
            this.originalPrice = data.sellingPrice
          }
        }
        this.$toast.clear()
      });
    },
    priceFormat(num) {
      return priceFormat(num);
    },
    getSkusAndPrice(find, arr) {
      let skuMap = {}
      this.allSkus.forEach((item) => {
        const attrIds = item.attrs.map(attr => attr.attrValueId).join(',')
        if (skuMap[attrIds]) return
        skuMap[attrIds] = {
          title: item.attrs.map(attr => attr.attrName && attr.attrValueName ? `${attr.attrName}: ${attr.attrValueName}` : ''),
          coverImg: item.coverImg,
          discountPrice: item.discountPrice,
          sellingPrice: item.sellingPrice,
          skuId: item.skuId,
          img: item?.img || this.defaultImageList,
          hidden: item.hidden,
          price: item.price,
        }
      })
      const attrIds = find ? arr.join(',') : this.activeAttrs.join(',')
      if (skuMap[attrIds] && !find) {
        this.currentSkuTitle = skuMap[attrIds].title
        this.goods_info.discountPrice = skuMap[attrIds].discountPrice || skuMap[attrIds].sellingPrice
        this.currentSkuId = skuMap[attrIds].skuId
        this.currentCoverImg = skuMap[attrIds].coverImg
        this.imageList = skuMap[attrIds].img
        this.btnDisabled = false
        this.originalPrice = skuMap[attrIds].discountPrice ? skuMap[attrIds].price : 0
      } else {
        if (Object.keys(skuMap).length === 0) {
          this.btnDisabled = false
        } else {
          this.btnDisabled = true
        }
        return skuMap[attrIds]
      }
    },
    handleToggle(info, index, dis, bool) {
      if (dis) return
      const disAttr = new Set();
      const allGood = this.goods_info?.canSelectAttributes?.goodAttrs
      const temparr = JSON.parse(JSON.stringify(this.activeAttrs))
      if (allGood.length === this.activeAttrs.length) {
        allGood.forEach((item, i) => {
          if (i != index) {
            item.attrValues.forEach((attr, j) => {
              if (attr.attrValueId !== info.attrValueId) {
                temparr[i] = attr.attrValueId
                if (!this.getSkusAndPrice(true, temparr)) {
                  disAttr.add(attr.attrValueId)
                  this.$set(this.activeAttrs, index, info.attrValueId);
                }
              }
            })
          }
        })
      }

      this.allSkus.flatMap(item => item.attrs)
        .filter(attr => attr.hidden && attr.attrValueId !== info.attrValueId)
        .forEach(attr => disAttr.add(attr.attrValueId));

      allGood.forEach(item => {
        item.attrValues.forEach(attr => {
          attr.disabled = disAttr.has(attr.attrValueId);
        });
      });
      this.$set(this.activeAttrs, index, info.attrValueId);
      this.getSkusAndPrice()
      disAttr.clear()
      this.$forceUpdate();
      !bool && this.handleToggle(info, index, dis, true)
    },
    //添加购物车
    addCart() {
      this.getSkusAndPrice()
      if (isLogin()) {
        if (this.goods_info?.isShelf == 0) {
          this.$notifyWarn(this.$t("该商品已下架"));
          return
        }
        // this.productPropertiesShow = this.cardShow = false;
        let productList = [];
        if (JSON.stringify(this.goods_info) == "{}") {
          console.log("商品数据有误,无法添加");
          return;
        }
        //添加选择数量
        this.goods_info.count = this.bugNum;
        this.goods_info.skuId = this.currentSkuId;
        this.goods_info.coverImg = this.currentCoverImg;
        this.goods_info.tempId = new Date().getTime();

        if (this.$ls.get("productList")) {
          productList = this.$ls.get("productList") || [];
          //验证是否已添加过
          let ishave = true;
          try {
            productList.forEach((item) => {
              if (item.id == this.goods_info.id && item.skuId == this.goods_info.skuId) {
                item.count += this.bugNum;
                this.cartNum += this.bugNum;
                // Toast(this.$t("购物车添加成功"));
                this.$notify(this.$t('购物车添加成功'), 'success')
                this.hide()
                // Toast(this.$t('购物车已存在此商品'))
                ishave = false;
                throw "跳出添加";
              }
            });
          } catch (e) {
            //购物数量添加,重置购物车
            this.$ls.set("productList", productList);
            this.$ls.remove("cartList");
          }
          //添加
          if (ishave) {
            if (this.goods_info.storeName == "") {
              // return Toast(this.$t("购物车添加失败, 请返回重试"));
              return this.$notify(this.$t('购物车添加失败, 请返回重试'))
            }
            productList.push(this.goods_info);
            this.$ls.set("productList", productList);
            this.cartNum = productList.reduce(function (prev, cur) {
              return (prev += cur.count);
            }, 0);
            // Toast(this.$t("购物车添加成功"));
            this.$notify(this.$t('购物车添加成功'), 'success')
            this.hide()
            this.$ls.remove("cartList");
          }
        } else {
          if (this.goods_info.storeName == "") {
            return this.$notify(this.$t('购物车添加失败, 请返回重试'))
          }
          productList.push(this.goods_info);
          this.$ls.set("productList", productList);
          this.cartNum = productList.reduce(function (prev, cur) {
            return (prev += cur.count);
          }, 0);
          // Toast(this.$t("购物车添加成功"));
          this.$notify(this.$t('购物车添加成功'), 'success')
          this.hide()
          this.$ls.remove("cartList");
        }
        // console.log(this.$ls.get('productList'))
        // this.$ls.clear()
      } else {
        // this.productPropertiesShow = this.cardShow = false;
        //   Toast(this.$t("请先登录"));
        // Dialog.confirm({
        //     title: this.$t("您还未登录"),
        //     message: this.$t("是否跳转到登录页面"),
        //     confirmButtonText: this.$t("确认"),
        //     cancelButtonText: this.$t("取消"),
        // }).then(() => {
        //     this.$router.push("/login");
        // });
        this.$notifyWarn(this.$t("请先登录"));
        this.$router.push("/login");
      }
    },
    //跳转下单
    openPay() {
      if (!isLogin()) {
        this.$notifyWarn(this.$t("请先登录"));
        this.$router.push("/login");
        return;
      }
      if (this.goods_info?.isShelf == 0) {
        this.$notifyWarn(this.$t("该商品已下架"));
        return
      }
      localStorage.setItem("sellerId", this.goods_info.sellerId);
      localStorage.setItem("storeName", this.goods_info.storeName);
      this.goods_info.tempId = new Date().getTime();
      this.hide()
      //type:1直接购买,2购物车购买
      this.$router.push({
        path: "/orderComnfirmation",
        query: {
          skuId: this.currentSkuId,
          type: 1,
          goodsInfo: JSON.stringify(this.goods_info),
          bugNum: this.bugNum,
          isCart: 0,
          currentCoverImg: this.currentCoverImg
        },
      });
    },
    //收藏商品
    addKeepGoods() {
      if (!isLogin()) {
        this.$notifyWarn(this.$t("请先登录"));
        this.$router.push("/login");
        return;
      }

      if (this.goods_info.isKeep == 1) {
        let dataJson = {
          sellerGoodsId: this.sellerGoodsId,
        };
        keepGoodsDel(dataJson).then(() => {
          Toast(this.$t("取消成功"));
          this.getInfo();
        });
      } else {
        let dataJson = {
          sellerGoodsId: this.sellerGoodsId,
        };
        keepGoods(dataJson).then(() => {
          Toast(this.$t("收藏成功"));
          this.getInfo();
        });
      }
    },
    // 打开客服
    openCustomer() {
      localStorage.setItem("sellerId", this.goods_info.sellerId);
      localStorage.setItem("storeName", this.goods_info.storeName);
      this.hide()
      if (isLogin()) {
        // Toast(this.$t("请先登录"));
        sessionStorage.setItem('shopName', this.SellerInfo.name)
        this.$router.push({ path: `/customerServiceIndex?goodsId=${this.goods_info.id}` });
      } else {
        this.$notifyWarn(this.$t("请先登录"));
        this.$router.push("/login");
      }
    },
    changeIndex(index) {
      this.$refs.swiperRef.swipeTo(index);
    },
  }
}
</script>

<template>
  <van-popup v-model="popupShow" :style="{ height: '95%',width: '95%' }">
    <div class="close" @click="hide">
      <img src="@/assets/image/commodity/guanbi.png" alt="">
    </div>
    <div v-if="loading" class="loading_box">
      <van-loading />
    </div>
    <div v-else>
      <div class="banner-product">
        <van-swipe :autoplay="3000" ref="swiperRef" :show-indicators="false" @change="onChange" style="direction: ltr;">
          <van-swipe-item class="swipe-item" v-for="(item, index) in imageList" :key="index">
            <img :src="item" class="img" />
          </van-swipe-item>
        </van-swipe>
      </div>
      <div class="ks_daohang">
        <div v-for="(item, index) in imageList" :key="index" class="indicator" :class="{ 'active-dot': checkActiveDot(index) }" @click="changeIndex(index)">
          <img :src="item" alt="">
        </div>
      </div>
      <div class="product-info-wrap">
        <div class="product-name">
          {{ goods_info.name }}
        </div>
        <div class="price-box">
          <div class="product-price">
            <!--          <span class="title">{{ $t("单价") }}</span>-->
            <span class="money">${{
                priceFormat(goods_info.discountPrice)
                  ? priceFormat(goods_info.discountPrice)
                  : priceFormat(goods_info.sellingPrice)
              }}</span>
            <!-- <span class="text">{{$t('价格')}}&nbsp;$56.12</span> -->
          </div>
          <div class="product-sellingPrice" v-if="originalPrice">
            <span class="title">{{ $t("原价") }}</span>
            <span class="money">${{ priceFormat(originalPrice) }}</span>
          </div>
          <div class="product-sold">
            {{ $t("销量") }} {{ priceFormatInt(goods_info.soldNum) }}
          </div>
        </div>
        <div class="sku_box" v-if="goods_info?.canSelectAttributes?.goodAttrs.length">
          <div class="attributes_box">
            <div class="attributes" v-for="(item, i) of goods_info?.canSelectAttributes?.goodAttrs" :key="i">
              <div class="p_title" v-if="item?.attrName">{{ currentSkuTitle[i] }}</div>
              <ul v-if="item?.attrName">
                <li :class="[sub.attrValueId == activeAttrs[i] && 'active', sub?.icon && 'img_box', sub.disabled && 'disabled']"
                    @click="handleToggle(sub, i, sub.disabled)" v-for="(sub, j) of item.attrValues" :key="j">
                  <img v-if="sub?.icon" :src="sub.iconImg" alt="">
                  <span v-else>{{ sub.attrValueName }}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="product-line-item">
<!--          <div class="left">{{ $t("已选数量") }}</div>-->
          <div class="right">
            <van-stepper :disable-input="true" :max="maxBuyNum" integer v-model="bugNum" />
          </div>
          <div class="button">
            <van-button :disabled="btnDisabled" type="primary" class="btn" @click="addCart">{{ $t("加入购物车") }}</van-button>
            <van-button :disabled="btnDisabled" type="primary" class="btn" @click="openPay">{{ $t("立即购买") }}</van-button>
          </div>
        </div>
        <div class="Total_Price">
          <p>{{ $t("总价") }}:</p>
          <p>
            ${{ priceFormat($operation(goods_info.discountPrice, bugNum, 'times')) ||
          priceFormat($operation(goods_info.sellingPrice, bugNum, 'times')) }}
          </p>
        </div>
        <div class="bott_opr">
          <div class="item" @click="addKeepGoods">
            <div class="icon" :class="[
                        goods_info.isKeep == 1 ? 'collect-check-icon' : 'collect-icon',
                    ]"></div>
            <div class="text">{{ $t(collectTitle) }}</div>
          </div>
          <div class="item" @click="openCustomer()">
            <div class="icon kefu-icon"></div>
            <div class="text">{{ itemName == 'FamilyMart' ? $t("联系商家") : $t("客服") }}</div>
          </div>
        </div>

      </div>
    </div>


  </van-popup>
</template>

<style scoped lang="scss">
.close {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  border-bottom: 1px solid #ededed;
  padding: 0 30px;
  >img{
    width: 25px;
    height: 25px;
  }
}
.loading_box{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.banner-product {
  width: 100%;
  // margin-top: 10px;
  //   filter: drop-shadow(0px 6px 12px rgba(55, 63, 69, 0.1));
  border-radius: 4px;
  position: relative;
  min-height: calc(100vw + 10px);

  .van-swipe {
    min-height: calc(100vw + 10px);
  }

  .swipe-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vw;

    .img {
      max-width: 100%;
      max-height: 100%;
      margin: 0 auto;
      // transform: translateY(-10px);
    }
  }
}
.ks_daohang {
  margin: 0 20px;
  overflow-x: scroll;
  display: flex;
  align-items: center;
  height: 92px;
  .indicator{
    flex-shrink: 0;
    margin-right: 10px;
    width: 87px;
    height: 89px;
    border: 1px solid #eee;
    box-sizing: border-box;
    border-radius: 4px;
    padding: 5px;
    cursor: pointer;
    >img{
      width: 100%;
      height: 100%;
      max-width: 87px;
      object-fit: contain;
    }
  }
  .active-dot{
    border: 1px solid var(--main-color);
  }
}
.product-info-wrap {
  padding: 0 20px;

  .product-name {
    font-weight: 600;
    font-size: 20px;
    padding: 15px 0;
    //border-bottom: 1px solid #eeeeee;
  }

  .price-box {
    //display: flex;
    //justify-content: space-between;
    //align-items: center;
    //height: 30px;
    //border-bottom: 1px solid #eeeeee;
    padding: 10px 0;
    overflow-x: auto;
    overflow-y: hidden;
    line-height: 18px;
    scrollbar-width: none;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
      display: none;
    }

    .product-sold {
      margin-top: 10px;
      font-size: 14px;
      color: #606266;
      white-space: nowrap;
    }

    .product-sellingPrice {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #999999;
      line-height: 18px;
      white-space: nowrap;
      margin: 0 20px;

      .title {
        font-size: 12px;
        line-height: 18px;
      }

      .money {
        text-decoration: line-through;
        margin-left: 10px;
        font-size: 14px;
        //line-height: 18px;
      }
    }

    .product-price {
      white-space: nowrap;

      .title {
        color: #999999;
        font-size: 14px;
      }

      .money {
        // color: hsl(37, 100%, 49%);
        color: var(--main-color);
        font-size: 16px;
        font-weight: 500;
        //margin-left: 10px;
      }

      .text {
        margin-left: 15px;
        color: #999999;
        font-size: 12px;
        text-decoration: line-through;
      }
    }
  }

  .sku_box {
    //border-bottom: 1px solid #eee;
    padding: 20px 0 15px 0;

    .attributes_box {
      max-height: 330px;
      overflow-y: auto;
      scrollbar-width: none;
      -ms-overflow-style: none;

      &::-webkit-scrollbar {
        display: none;
      }
    }

    .attributes {

      .p_title {
        font-size: 14px;
        margin-bottom: 10px;
      }

      ul {
        display: flex;
        // flex-wrap: wrap;
        overflow-x: auto;
        scrollbar-width: none;
        -ms-overflow-style: none;

        &::-webkit-scrollbar {
          display: none;
        }

        li {
          // width: 100px;
          // flex: 0 0 100px;
          padding: 5px 16px;
          background: #f2f2f2;
          margin-right: 10px;
          margin-bottom: 10px;
          border-radius: 4px;
          // min-width: 38px;
          // min-height: 38px;
          border: 1px solid #eee;
          display: flex;
          justify-content: center;
          align-items: center;
          white-space: nowrap;

          img {
            max-width: 25px;
            max-height: 25px;
          }
          span{
            font-size: 15px;
          }

          &.active {
            background: var(--main-color);
            color: #fff !important;
          }

          &.disabled {
            color: #A3A3A3;
            opacity: .8;
            // opacity: .5;
          }

          &.img_box {
            min-width: 38px;
            min-height: 38px;
            padding: 0;
            background: #fff;

            &.disabled {
              border: 1px dashed #eee !important;
              background: transparent !important;
              opacity: .5;
              // -webkit-filter: grayscale(100%);
              // -moz-filter: grayscale(100%);
              // -ms-filter: grayscale(100%);
              // -o-filter: grayscale(100%);
              // filter: grayscale(100%);
              // filter: gray;
            }

            &.active {
              border-color: var(--main-color);
            }
          }
        }
      }
    }
  }


  .product-line-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    //border-bottom: 1px solid #eeeeee;
    padding: 15px 0;

    .left {
      // flex: 1;
      // min-width: 10px;
      margin-right: 10px;
    }

    .right {
      flex-shrink: 0;
      //flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .button{
      .btn {
        margin-left: 10px;
        background: var(--main-color);
        border: none;
        border-radius: 4px;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }
  }
  .Total_Price{
    display: flex;
    align-items: center;
    padding: 10px 0;
    color: #606266;
    font-size: 16px;
  }
  .bott_opr {
    padding: 20px 0 36px 0;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .item {
      //flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-right: 30px;

      .text {
        font-size: 16px;
        color: #606060;
      }

      .icon {
        width: 18px;
        height: 18px;
        margin-right: 5px;
        position: relative;
      }

      .collect-icon {
        background: url("@/assets/image/commodity/Star6.png") center no-repeat;
        background-size: 100% 100%;
      }

      .collect-check-icon {
        background: url("@/assets/image/commodity/Star7.png") center no-repeat;
        background-size: 100% 100%;
      }

      .kefu-icon {
        background: url("@/assets/image/commodity/kefu.png") center no-repeat;
        background-size: 100% 100%;
      }

      .kefu-icon {
        background: url("@/assets/image/commodity/kefu.png") center no-repeat;
        background-size: 100% 100%;
      }
    }
  }
}
</style>
